<template>
  <div class="app-container">
    <tab-selector
      v-model="currentTabSelector"
      :options="tabSelectorOptions"
      @tab-change="handleTabChange"
    ></tab-selector>

    <el-form ref="queryForm" :model="queryParams" :inline="true">
      <el-row>
        <el-form-item label="回访时间">
          <el-date-picker
            :value="visitTime"
            type="daterange"
            :editable="false"
            :clearable="false"
            :picker-options="pickerOptions"
            format="yyyy-MM-dd HH:mm"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @input="handleVisitTime"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            :value="createTime"
            type="daterange"
            :editable="false"
            :picker-options="pickerOptions"
            format="yyyy-MM-dd HH:mm"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @input="handleCreateTime"
          ></el-date-picker>
        </el-form-item>
        <el-form-item
          label="医生"
          prop="visitDoctor"
          class="datetimerange"
          style="margin-top: 0px"
        >
          <el-select
            v-model="queryParams.visitDoctor"
            filterable
            clearable
            placeholder="请选择医生"
            @change="selectDoctor"
          >
            <el-option
              v-for="item in doctorList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="small"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="small" @click="resetQuery"
            >重置</el-button
          >
          <el-button
            type="warning"
            icon="el-icon-full-screen"
            size="small"
            @click="handleExport"
            >导出</el-button
          >
        </el-form-item>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb20">
      <el-col :span="1.5">
        <columns-filter-button />
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      stripe
      border
      :data="returnList"
      :height="clientHeight"
      :max-height="clientHeight"
      @row-dblclick="handleDoubleDetails"
      @row-click="handleDetails"
    >
      <el-table-column type="index" fixed="left"></el-table-column>
      <columns-filter-view>
        <el-table-column
          label="病例号"
          align="center"
          prop="yiyaClinicPerson.caseNumber"
          min-width="120"
        />
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="患者姓名"
          align="center"
          prop="yiyaClinicPerson.name"
          :min-width="'到店状态'.length * 30"
        >
          <template slot-scope="scope">
            <div style="cursor: pointer">
              {{ scope.row.yiyaClinicPerson.name }}
            </div>
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="联系电话"
          align="center"
          :min-width="'手机号码'.length * 50"
        >
          <template slot-scope="scope">
            <hover-phone :items="scope.row.yiyaClinicPerson" :type="1" />
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="随访医生"
          align="center"
          prop="yiyaVisitDoctor.visitDoctor"
          min-width="100"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="咨询师"
          align="center"
          prop="yiyaClinicPerson.firstTc"
        />
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="创建人"
          align="center"
          prop="yiyaVisitDoctor.createBy"
        />
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="回访内容"
          align="center"
          prop="yiyaVisitDoctor.contet"
          min-width="180"
        />
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="回访结果"
          align="center"
          prop="yiyaVisitDoctor.result"
          min-width="180"
        />
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="跟踪状态"
          align="center"
          prop="yiyaVisitDoctor.trackStatus"
          column-key="trackStatus"
          min-width="100"
        >
          <template slot-scope="scope">
            {{ trackingStatusEnum[scope.row.yiyaVisitDoctor.trackStatus] }}
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="计划回访时间"
          align="center"
          prop="yiyaVisitDoctor.visitTime"
          min-width="180"
        >
          <template slot-scope="scope">
            {{
              dayjs(scope.row.yiyaVisitDoctor.visitTime).format(
                'YYYY-MM-DD HH:mm:ss'
              )
            }}
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="回访状态"
          align="center"
          prop="visitStatus"
          :min-width="'到店状态'.length * 30"
        >
          <template slot-scope="scope">
            {{ returnVisitStatusEnum[scope.row.yiyaVisitDoctor.visitStatus] }}
          </template>
        </el-table-column>
      </columns-filter-view>

      <columns-filter-view>
        <el-table-column label="操作" align="center" min-width="100">
          <el-dropdown slot-scope="scope">
            <span class="el-dropdown-link">
              操作<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                @click.native="
                  handleReturnVisitEditor(
                    scope.row.yiyaClinicPerson,
                    scope.row.yiyaVisitDoctor
                  )
                "
              >
                编辑随访
              </el-dropdown-item>
              <el-dropdown-item
                v-if="
                  returnVisitStatusEnum[
                    scope.row.yiyaVisitDoctor.visitStatus
                  ] === '待计划'
                "
                @click.native="handleComplete(scope.row.yiyaVisitDoctor)"
              >
                完成回访
              </el-dropdown-item>
              <el-dropdown-item
                @click.native="handleDelete(scope.row.yiyaVisitDoctor)"
              >
                删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-table-column>
      </columns-filter-view>
      <empty slot="empty"></empty>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getListDoctor"
    ></pagination>
    <update-visit
      v-model="returnVisitEditor.visible"
      :patient="returnVisitEditor.patient"
      :data="returnVisitEditor.data"
      :doctor-list="doctorList"
      @ok="getAddVisis"
      @close="handleClose"
    ></update-visit>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { mapState } from 'vuex'
import { postName } from '@/api/system/user'
import {
  listDoctorAll,
  getDoctor,
  delDoctor,
  addDoctor,
  updateDoctor,
  exportDoctor,
} from '@/api/services/doctor'
import { encode } from '@/utils/utils'
import {
  getThisWeekStartWithEnd,
  getTodayStartWithEnd,
  getYesterdayStartWithEnd,
  getThisMonthStartWithEnd,
  formatStartWithEnd,
  getTomorrowStartWithEnd,
  startWithEndMap,
} from '@/utils/date'
import {
  consumptionStatusOptions,
  returnVisitStatusOptions,
} from '@/utils/options'
import { returnVisitStatusEnum, trackingStatusEnum } from '@/utils/enums'

import TabSelector from '@/components/yiya/TabSelector'
import Empty from '@/components/yiya/Empty'
import {
  ColumnsFilterButton,
  ColumnsFilterView,
} from '@/components/yiya/TableColumnsFilter'
import hoverPhone from '@/components/yiya/hoverPhone'
import updateVisit from '@/views/components/TabsPanes/FollowupVisitPane/updateVisit'

const QUERY_PARAMS = {
  pageNum: 1,
  pageSize: 50,
  visitDoctor: undefined,
  startVisitTime: undefined,
  endVisitTime: undefined,
  startCreateTime: undefined,
  endCreateTime: undefined,
  orderByColumn: 'visitTime',
  isAsc: 'desc',
}

export default {
  name: 'DoctorVisit',
  components: {
    TabSelector,
    Empty,
    ColumnsFilterButton,
    ColumnsFilterView,
    hoverPhone,
    updateVisit,
  },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      returnList: [],
      tcList: [],
      doctorList: [],
      queryParams: {},
      currentTabSelector: ' ',
      defaultUser: {},
      visitTime: [],
      visitFinishTime: [],
      createTime: [],
      pickerOptions: {
        firstDayOfWeek: 1,
        shortcuts: [
          {
            text: '今日',
            onClick(picker) {
              const time = getTodayStartWithEnd()
              picker.$emit('pick', time)
            },
          },
          {
            text: '昨日',
            onClick(picker) {
              const time = getYesterdayStartWithEnd()
              picker.$emit('pick', time)
            },
          },
          {
            text: '本周',
            onClick(picker) {
              const time = getThisWeekStartWithEnd()
              picker.$emit('pick', time)
            },
          },
          {
            text: '本月',
            onClick(picker) {
              const time = getThisMonthStartWithEnd()
              picker.$emit('pick', time)
            },
          },
        ],
      },
      returnVisitEditor: {
        visible: false,
        patient: {},
        data: {},
      },
      clientHeight: document.body.clientHeight - 333,
    }
  },
  computed: {
    ...mapState({
      clinicId: (state) => state.clinic.clinicId,
      userName: (state) => state.user.name,
    }),
    dayjs() {
      return dayjs
    },
    trackingStatusEnum() {
      return trackingStatusEnum
    },
    consumptionStatusOptions() {
      return consumptionStatusOptions.map(({ label, value }) => ({
        text: label,
        value,
      }))
    },
    returnVisitStatusEnum() {
      return returnVisitStatusEnum
    },
    tabSelectorOptions() {
      return [
        {
          label: '总数',
          value: ' ',
        },
        ...returnVisitStatusOptions.map(({ label, value }) => ({
          label,
          value: label,
          params: value,
        })),
      ]
    },
  },
  async mounted() {
    await this.getUserListAll()
    this.defaultUser = this.doctorList.find(
      (item) => item.userName === this.userName
    )
    if (this.defaultUser !== undefined) {
      QUERY_PARAMS.visitDoctor = this.defaultUser.userName
    } else {
      QUERY_PARAMS.visitDoctor = this.doctorList[0].userName
    }
    this.queryParams = {
      ...QUERY_PARAMS,
      ...this.$route.query,
    }
    const today = getTodayStartWithEnd()
    this.handleVisitTime(today)
    // this.handleCreateTime(today)
  },
  methods: {
    getAddVisis() {
      this.returnVisitEditor.visible = false
      this.getListDoctor()
    },
    handleClose() {
      this.returnVisitEditor.visible = false
    },
    async getUserListAll() {
      const { data } = await postName({
        deptId: +this.clinicId,
        postname: '医生',
      })
      this.doctorList = data
    },
    selectDoctor(e) {
      this.queryParams.visitDoctor = e
      this.handleQuery()
    },
    async getListDoctor() {
      try {
        this.loading = true
        const { rows, total } = await listDoctorAll(this.queryParams)
        this.returnList = rows
        this.total = total
      } finally {
        this.loading = false
      }
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getListDoctor()
    },
    resetQuery() {
      this.queryParams.startCreateTime = undefined
      this.queryParams.endCreateTime = undefined
      this.queryParams.visitDoctor = undefined
      this.handleQuery()
    },
    handleDoubleDetails(row) {
      const menu = this.$route.path.slice(0, this.$route.path.lastIndexOf('/'))
      this.$router.push(
        `${menu}/details?id=${row.yiyaClinicPerson.id}&redirect=${encode({
          path: this.$route.path,
          query: this.queryParams,
        })}`
      )
    },
    handleDetails(...row) {
      if (row[2].target._prevClass === undefined) {
        this.handleDoubleDetails(row[0])
      }
    },
    handleTabChange({ params }) {
      this.queryParams.visitStatus = params
      this.handleQuery()
    },
    handleVisitTime(e) {
      const { time, start, end } = formatStartWithEnd(e)
      this.visitTime = time
      this.queryParams.startVisitTime = start
      this.queryParams.endVisitTime = end
      this.handleQuery()
    },
    handleCreateTime(e) {
      const { time, start, end } = formatStartWithEnd(e)
      this.createTime = time
      this.queryParams.startCreateTime = start
      this.queryParams.endCreateTime = end
      this.handleQuery()
    },
    handleReturnVisitEditor(patient, visit) {
      this.returnVisitEditor = {
        visible: true,
        patient,
        data: visit || {},
      }
    },
    async handleComplete(visit) {
      const { value: result } = await this.$prompt('回访结果', '完成回访', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入回访结果',
        inputValidator: (e) => !!(e && e.trim()),
        inputErrorMessage: '回访结果不能为空',
      })
      await updateDoctor({
        id: visit.id,
        result,
        visitStatus: returnVisitStatusEnum['已完成'],
        visitFinishTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      })
      this.msgSuccess('回访完成')
      await this.getListDoctor()
    },
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有市场建档数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => exportDoctor(queryParams))
        .then((response) => this.download(response.msg))
    },
    async handleDelete(visit) {
      await this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      await delDoctor(visit.id)
      this.msgSuccess('删除成功')
      await this.getListDoctor()
    },
  },
}
</script>

<style lang="scss" scoped>
.content {
  margin-top: -6px;
  height: 20px;
}
</style>
